package gwtI18nEditor.widgets;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import gwtI18nEditor.datamodel.Message;
import gwtI18nEditor.datamodel.MessageType;
import gwtI18nEditor.datamodel.Translation;
import gwtI18nEditor.resources.EscapeTable;

import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

@SuppressWarnings("serial")
public abstract class TranslationEditor extends JPanel implements DocumentListener, KeyListener {
	
	private JTextArea   editor;
	private Translation content = null;
	private boolean     isHTML  = true;

	public TranslationEditor() {
		super(new BorderLayout());
		editor = new JTextArea();
		editor.getDocument().addDocumentListener(this);
		editor.addKeyListener(this);
		editor.setWrapStyleWord(true);
		editor.setLineWrap(true);
		JScrollPane scroller = new JScrollPane(editor);
		scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		JMenuBar menu = new EditorShortcuts() {
			@Override
			public void onSelect(char text) {
				editor.dispatchEvent(new KeyEvent(editor,
					    KeyEvent.KEY_TYPED, System.currentTimeMillis(),
					    0, KeyEvent.VK_UNDEFINED, text));
			}};
		add(menu,     BorderLayout.PAGE_START);
		add(scroller, BorderLayout.CENTER);
	}
	
	public void updateEditor(Message message) {
		isHTML = message.getType()==MessageType.SAFEHTML;
		for (Translation translation: message.getTranslations()) {
			if (translation.getLocale()!=null) {
				updateEditor(translation);
				return;
			}
		}
	}
	
	public void updateEditor(Translation translation) {
		content = null;
		editor.setText(EscapeTable.unescape(translation.getMessage(), isHTML));
		content = translation;
	}

	@Override
	public void changedUpdate(DocumentEvent event) {
		if (content!=null) content.setMessage(EscapeTable.escape(editor.getText(), isHTML));
	}

	@Override
	public void insertUpdate(DocumentEvent event) {
		if (content!=null) content.setMessage(EscapeTable.escape(editor.getText(), isHTML));
	}

	@Override
	public void removeUpdate(DocumentEvent event) {
		if (content!=null) content.setMessage(EscapeTable.escape(editor.getText(), isHTML));
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode()==KeyEvent.VK_ENTER) {
			onEnter(e.getModifiers()>0);
			e.consume();
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {}

	@Override
	public void keyTyped(KeyEvent e) {}
	
	public abstract void onEnter(boolean shift);
}
